package com.bd.scm.module.common;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.scm.dao.mapper.system.CommonMapper;
import com.bd.scm.domain.dto.error.StoreResultDetailDto;
import com.bd.scm.domain.dto.error.StoreResultDto;
import com.bd.scm.module.enums.CodeRuleEnum;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    @Autowired
    private CommonMapper commonMapper;

    /**
     * 获取顺序编号
     *
     * @param codeRuleEnum
     * @return
     */
    public String getNumber(CodeRuleEnum codeRuleEnum) {
        HashMap map = new HashMap();
        map.put("classId", codeRuleEnum.getCode());

        commonMapper.getNumber(map);
        String number = map.get("number").toString();

        return number;
    }

    /**
     * 获取表最大Id
     *
     * @param codeRuleEnum
     * @return
     */
    public Integer getMaxId(CodeRuleEnum codeRuleEnum) {
        HashMap map = new HashMap();
        map.put("classId", codeRuleEnum.getCode());

        commonMapper.getMaxId(map);
        Integer id = Integer.parseInt(map.get("interId").toString());

        return id;
    }

    /**
     * 获取分页总数
     * @param pageSize  每页显示记录数
     * @param dataTotal 记录总数
     * @return
     */
    public Integer getPageTotal(int pageSize, int dataTotal) {
        return dataTotal  % pageSize == 0 ? dataTotal / pageSize : dataTotal / pageSize + 1;
    }

    /**
     * 转换存储过程返回的错误信息
     * @param msg
     * @return
     */
    public List<StoreResultDetailDto> getStoreResultMsg(String msg) {
        if (ObjectUtil.isEmpty(msg)) {
            return null;
        }

        List<StoreResultDto> listResult = JSON.parseArray(msg, StoreResultDto.class);

        if (ObjectUtil.isEmpty(listResult)) {
            return null;
        }
        List<StoreResultDetailDto> listError = JSON.parseArray(listResult.get(0).getMsg(), StoreResultDetailDto.class);
        return listError;
    }
}